from scopt.util.message_types import STRING
from scopt.util import message as msg_util
from . import message


@message(type='context.tenant.create',
         version='0.1',
         reqd={'tenant_name': STRING(required=True, doc=\
'''Name of tenant to create.'''),
               'params': {'param_name': 'param_value'}},
         resd={'tenant_id': STRING(required=True, doc=\
'''ID of tenant, requested to create.'''),
               'tenant_name': STRING(required=True, doc=\
'''Name of tenant''')})
def handle(data_packet, context):
    reqd = msg_util.get_request_data(data_packet)
    tenant_name = reqd['tenant_name']
    # TODO: make tenant_id generation independent of tenant_name
    #       and driver dependent
    tenant_id = tenant_name.upper().replace(' ', '')
    context.tx_begin()
    try:
        # 1. Create tenant entry
        context.insert('tenants', values={'id': tenant_id,
                                          'name': tenant_name})
        # 2. Create tenant user association
        login = data_packet['security']['principal']['login']
        context.insert('users_tenants', values={'login': login,
                                                'tenant_fk': tenant_id})
        # 3. Insert tenant creation parameters
        for param_name, param_value in reqd['params'].items():
            context.insert('tenants_params',
                           values={'tenant_fk': tenant_id,
                                   'param_name': str(param_name),
                                   'param_value': str(param_value),
                                   'scope': 'public'})
        # 4. Create ds entry
        result = context.query('ds',
                               columns=['ds.id'],
                               where=[['ds.url', context.lds_bds_url]])
        if len(result) == 0:
            datasource_id = context.insert('ds',
                                           values={'url': context.lds_bds_url})
        else:
            datasource_id = result[0]['id']
        # 5. Create lds/BDS entry parameter
        param_value = '{DS_ID}.{SCHEMA}'.format(DS_ID=datasource_id,
                                                SCHEMA=context.lds_bds_schema)
        context.insert('tenants_params', values={'tenant_fk': tenant_id,
                                                'param_name': 'lds/BDS',
                                                'param_value': param_value,
                                                'scope': 'private'})
        context.tx_commit()
    except:
        context.tx_rollback()
        raise
    data_packet = msg_util.set_tenant_id(data_packet, tenant_id)
    data_packet = context.request_context_init(data_packet)
    return msg_util.ok_response(data_packet, handle,
                                {'tenant_id': tenant_id,
                                 'tenant_name': tenant_name})
